<?php

namespace App\Services\MakeBoxProductOrder;

use App\Models\User;
use App\Models\Product;
use App\Models\Coupon;
use App\Models\Address;
use App\Models\BlindBox;
use App\Models\BlindBoxProduct;
use App\Models\BlindBoxLevelValue;
use App\Models\BlindBoxOrder;
use App\Models\ProductSku;
use Brick\Math\RoundingMode;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class RefreshBoxProductOrder
{
	protected ?User $user = null;

	protected ?BlindBoxOrder $order = null;

	/**
	 * sku_id, attr_value_index, amount.
	 */

	public function __construct(
		User $user,
		BlindBoxOrder $order,
	)
	{
		$this->user = $user;
		$this->order = $order;
	}

	protected function update()
	{
		DB::transaction(function () {

			$blindBoxProduct = $this->getRandomProduct();
			$product  = Product::find($blindBoxProduct->product_id);
			$sku  = $product->skus->first();

			$updateArr = [
				'user_id' => $this->user->id,
				'product_id' => $blindBoxProduct->product_id,
				'sku_id' => $sku->id,
				'cost' => $product->price_lowest_cost,
				'profit' => big_decimal($this->order->box_price)->minus($product->price_lowest_cost),
				'blind_box_level_id' => $blindBoxProduct->blind_box_level_id,
				'is_refresh' => true
			];


			$this->blind_order = $this->order->update($updateArr);

			$refreshCoupon = Coupon::where('coupon_category','refresh')->first();
			
			$coupon = $this->user->coupons->where('coupon_id',$refreshCoupon->id)->where('is_used',false)->first();
			
			$coupon->update(['is_used'=>true]);


		});

		return $this->blind_order;
	}

	public function getRandomProduct(){ 
		$levels = BlindBoxLevelValue::query()->used()->where('blind_box_id',$this->order->blind_box_id)->get();

		$merge = [];
		foreach($levels as $k => $v){

			$fill = array_fill(0,($v->rate*100),$v->blind_box_level_id);
			$merge = array_merge($merge,$fill);
		}
		
		$num=rand(0,count($merge));

		$level = $merge[$num];

		$blindBoxProduct = BlindBoxProduct::query()
						->where('blind_box_id',$this->order->blind_box_id)
						->where('blind_box_level_id',$level)
						->inRandomOrder()
						->take(1)->first();
		
		return $blindBoxProduct;
	}

	public function refresh()
	{
		return $this->update();
	}
}
